package com.teatime.client.utils;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

public class InputStreamArray extends InputStream {

	private int mCurr;
	
	private List<InputStream> mInputStreams;
	public InputStreamArray() {
		mInputStreams = new ArrayList<InputStream>();
		mCurr = 0;
	}
	
	public void add(InputStream is) {
		if (is != null) {
			mInputStreams.add(is);
		}
	}
	
	public void add(int index, InputStream is) {
		if (is != null) {
			if (index < 0) {
				index = 0;
			}
			mInputStreams.add(index, is);
		}
	}
	
	@Override
	public int read() throws IOException {
		// TODO Auto-generated method stub
		while(mCurr < mInputStreams.size()) {
			InputStream is = mInputStreams.get(mCurr);
			int ret = is.read();
			if (ret >= 0) {
				return ret;
			}
			mCurr ++;
		}
		return -1;
	}
	
	@Override
	public int read(byte b[], int off, int len) throws IOException {
		int orig_len = len;
		int read_len;
		while(mCurr < mInputStreams.size() && len > 0) {
			InputStream is = mInputStreams.get(mCurr);
			if (is.available() <= 0) {
				mCurr ++;
				continue;
			}
			read_len = Math.min(len, is.available());
			read_len = is.read(b, off, read_len);
			if (read_len >= 0) {
				off += read_len;
				len -= read_len;
			}
			else {
				mCurr ++;
			}
		}
		read_len = orig_len - len;
		if (read_len == 0 && mCurr >= mInputStreams.size()) {
			return -1;
		}
		return read_len;
	}
	
	public int available() throws IOException {
		int ret = 0, i;
		for (i = mCurr; i < mInputStreams.size(); i ++) {
			InputStream is = mInputStreams.get(i);
			ret += is.available();
		}
		return ret;
	}
	
	public void close() throws IOException {
		int i;
		for (i = 0; i < mInputStreams.size(); i ++) {
			InputStream is = mInputStreams.get(i);
			is.close();
		}
		mInputStreams.clear();
		mCurr = 0;
	}
	
	public void clear() {
		try {
			close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
	}
	
	public int size() {
		return mInputStreams.size();
	}
	
	public InputStream get(int index) {
		return mInputStreams.get(index);
	}

}
